package com.qb.main.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.ToastUtils
import com.qb.baselibrary.basekotlin.EmptyViewModel
import com.qb.common.base.CommonBaseFragment
import com.qb.common.bean.ImageBean
import com.qb.common.constant.Constants
import com.qb.common.router.RouterPath
import com.qb.common.utils.LitePalUtils
import com.qb.common.utils.ShareUtils
import com.qb.common.utils.ValidUtils
import com.qb.main.R
import com.qb.main.databinding.MainMainFragmentBinding
import com.qb.main.ui.adapter.ImageAdapter
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import kotlin.concurrent.thread
import kotlin.random.Random


/**
 * @ClassName: MainFragment
 * @Description: Description
 * @Author: qq
 * @Date: 2022/9/28 17:40
 */
@Route(path = RouterPath.Main.URL_Main_MainFragment)
class MainFragment:CommonBaseFragment<EmptyViewModel,MainMainFragmentBinding>(),View.OnClickListener {
    var page = 1
    var allBeans:ArrayList<ImageBean> = ArrayList()
    var type = 0
    var allTitleView:ArrayList<TextView> = ArrayList()
    private val imageAdapter by  lazy {
        ImageAdapter()
    }
    companion object{
        @SuppressLint("StaticFieldLeak")
        private var instance:MainFragment?=null
        @Synchronized
        fun get():MainFragment{
            if (null== instance) instance = MainFragment()
            return instance as MainFragment
        }
    }
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        mBinding.tvLxh.setOnClickListener(this)
        mBinding.tvEg.setOnClickListener(this)
        mBinding.tvQs.setOnClickListener(this)
        mBinding.tvTc.setOnClickListener(this)
        mBinding.tvDs.setOnClickListener(this)
        mBinding.tvCy.setOnClickListener(this)
        mBinding.tvNr.setOnClickListener(this)

        with(mBinding.recycle){
            adapter = imageAdapter
        }
        imageAdapter.apply {
            addChildClickViewIds(R.id.iv_gif)
            addChildClickViewIds(R.id.iv_png)
            addChildClickViewIds(R.id.tv_good)
            addChildClickViewIds(R.id.tv_bad)
            addChildClickViewIds(R.id.tv_share)
            setOnItemChildClickListener { adapter, view, position ->
                var imageBean = adapter.getItem(position) as ImageBean
                var userInfo = SPStaticUtils.getString(Constants.LOGININFO)
                when(view.id){
                    R.id.iv_gif->{

                    }
                    R.id.iv_png->{

                    }
                    R.id.tv_good->{
                        if (ValidUtils.isValid(userInfo)){
                            imageBean.good+=1
                            LitePalUtils.myLike(imageBean)
                        }else{
                            ToastUtils.showShort("请先登录")
                        }
                    }
                    R.id.tv_bad->{
                        if (ValidUtils.isValid(userInfo)){
                            imageBean.bad+=1
                            LitePalUtils.myBad(imageBean)
                        }else{
                            ToastUtils.showShort("请先登录")
                        }
                    }
                    R.id.tv_share->{
//                        val wechatIntent = Intent(Intent.ACTION_SEND)
//                        wechatIntent.setPackage("com.tencent.mm")
//                        wechatIntent.type = "text/plain"
//                        wechatIntent.putExtra(Intent.EXTRA_TEXT, imageBean.img)
//                        startActivity(wechatIntent)
                        ShareUtils.share(mContext,imageBean.img)
                    }
                }
                notifyItemChanged(position)
            }
        }
        getData()
        mBinding.smartRefresh.setOnRefreshListener {
            page=1
            getData()
        }
        mBinding.smartRefresh.setOnLoadMoreListener {
            page++
            getData()
        }
        mBinding.baseTitle.setTitle("零一-冷笑话大全")
        mBinding.baseTitle.leftBack.visibility = View.GONE
    }

    override fun onStart() {
        super.onStart()
        allTitleView.clear()
        allTitleView.add(mBinding.tvLxh)
        allTitleView.add(mBinding.tvEg)
        allTitleView.add(mBinding.tvQs)
        allTitleView.add(mBinding.tvTc)
        allTitleView.add(mBinding.tvDs)
        allTitleView.add(mBinding.tvCy)
        allTitleView.add(mBinding.tvNr)
    }
    private fun getData(){
        try {
            showLoading()
            allBeans.clear()
            var everyData :ArrayList<ImageBean> = ArrayList()
            thread {
                var url = "https://xiaohua.zol.com.cn/qutu/$page.html"
                when (type) {
                    0 -> {
                        url = "https://xiaohua.zol.com.cn/lengxiaohua/$page.html"
                    }
                    1 -> {
                        url = "https://xiaohua.zol.com.cn/qutu/egao/$page.html"
                    }
                    2 -> {
                        url = "https://xiaohua.zol.com.cn/qutu/qiushi/$page.html"
                    }
                    3 -> {
                        url = "https://xiaohua.zol.com.cn/qutu/tucao/$page.html"
                    }
                    4 -> {
                        url = "https://xiaohua.zol.com.cn/qutu/diaosi/$page.html"
                    }
                    5 -> {
                        url = "https://xiaohua.zol.com.cn/qutu/chuangyi/$page.html"
                    }
                    6 -> {
                        url = "https://xiaohua.zol.com.cn/qutu/niuren/$page.html"
                    }
                }
                try {
                    LogUtils.e("url:=$url")
                    val doc: Document = Jsoup.connect(url).get()
                    LogUtils.e(doc.title())
                    val elements = doc.select("li.article-summary")
                    for (element in elements) {
                        var articleTitle = try {
                            element.select("span.article-title").text()
                        } catch (e: Exception) {
                            "网络"
                        }
                        var articleSource = try {
                            element.select("div.article-source span")[1].text()
                        } catch (e: Exception) {
                            "网络"
                        }
                        var benContent = "未知"
                        try {
                            if (type==0){
                                val jokeContent = element.select("div.summary-text").text().replace("<p>","").replace("</p>","").replace("\\s+", "")
                                benContent = jokeContent
                            }else{
                                val imgSrc = element.select("div.summary-text img").attr("loadsrc")
                                benContent = imgSrc
                            }
                        } catch (e: Exception) {
                            benContent = "未知"
                        }

                        if (!TextUtils.isEmpty(benContent)&&benContent.endsWith(".gif")||benContent.endsWith(".jpg")||benContent.endsWith(".png")){
                            var imageBean = ImageBean()
                            imageBean.img = benContent
                            imageBean.title = "$articleTitle"
                            imageBean.from = articleSource
                            imageBean.good = Random.nextInt(0, 1001)
                            imageBean.bad = Random.nextInt(0, 1001)
                            allBeans.add(imageBean)
                            everyData.add(imageBean)
                        }else if (type==0){
                            var imageBean = ImageBean()
                            imageBean.img = benContent
                            imageBean.title = "$articleTitle"
                            imageBean.from = articleSource
                            imageBean.good = Random.nextInt(0, 1001)
                            imageBean.bad = Random.nextInt(0, 1001)
                            allBeans.add(imageBean)
                            everyData.add(imageBean)
                        }
                        try {
                            LogUtils.e("Article Title: $articleTitle"
                                ,"Article Source: $articleSource"
                                ,"Image Source: $benContent"
                            )
                        } catch (e: Exception) {
                        }
                    }
                    activity?.runOnUiThread {
                        dismissLoading()
                        if (page==1){
                            mBinding.smartRefresh.finishRefresh()
                            imageAdapter.setNewInstance(everyData)
                        }else {
                            imageAdapter.addData(everyData)
                            mBinding.smartRefresh.finishLoadMore()
                        }
                    }
                } catch (e: Exception) {
                    activity?.runOnUiThread {
                        dismissLoading()
                        try {
                            mBinding?.smartRefresh?.finishRefresh()
                            mBinding?.smartRefresh?.finishLoadMore()
                        } catch (e: Exception) {
                        }
                    }
                }

            }
        } catch (e: Exception) {
            activity?.runOnUiThread {
                dismissLoading()
                try {
                    mBinding?.smartRefresh?.finishRefresh()
                    mBinding?.smartRefresh?.finishLoadMore()
                } catch (e: Exception) {
                }
            }
        }
    }
    private fun setClickTitle(type:Int){
        for (index in 0 until allTitleView.size){
            allTitleView[index].setTextColor(Color.parseColor("#333333"))
            if (type==index){
                allTitleView[index].setTextColor(Color.parseColor("#BB996C"))
                mBinding.baseTitle.setTitle("零一-${allTitleView[index].text}大全")
            }
        }
    }
    override fun onClick(v: View?) {
        v?.let {
            try {
                mBinding?.smartRefresh?.finishRefresh()
                mBinding?.smartRefresh?.finishLoadMore()
            } catch (e: Exception) {
            }
            when(v.id){
                mBinding.tvLxh.id->{

                    type = 0
                    setClickTitle(type)
                    page = 1
                    getData()
                }
                mBinding.tvEg.id->{
                    type = 1
                    setClickTitle(type)
                    page = 1
                    getData()
                }
                mBinding.tvQs.id->{
                    type = 2
                    setClickTitle(type)
                    page = 1
                    getData()
                }
                mBinding.tvTc.id->{
                    type=3
                    setClickTitle(type)
                    page=1
                    getData()
                }
                mBinding.tvDs.id->{
                    type=4
                    setClickTitle(type)
                    page=1
                    getData()
                }
                mBinding.tvCy.id->{
                    type=5
                    setClickTitle(type)
                    page=1
                    getData()
                }
                mBinding.tvNr.id->{
                    type=6
                    setClickTitle(type)
                    page=1
                    getData()
                }
            }
        }
    }
}